#pragma rtGlobals=1		// Use modern global access method.
#pragma version = 1.1
#include <WaveSelectorWidget> // Includes the WaveSelectorWidget Procedure
#include <Peak AutoFind>

//---------------------------------------------------------------------------------------------------------
// Version 1.0:
// -Basic Data Import Functions
// -Basic Control Panel
// -Non-functional data processing check boxes
//---------------------------------------------------------------------------------------------------------
//Version 1.1:
//-TEY, TFY, and Normalize buttons now work
//---------------------------------------------------------------------------------------------------------
// Adds Menu
//---------------------------------------------------------------------------------------------------------
Menu "Spectrometry"
	"Load Data", spect_main()
	"Calibrate XAS", XAS_Ecal_Setup()
end

Menu "Spectrometry"
	Submenu "Load\Unload Package"
		"Unload Spectrometry Package", /Q, LoadProcedures_Shawn#Unload_Spectrometry_Procedures()
	End
End

//----------------------------------------------------------------------------------------------------------
// Main Procedure. Checks for existence of data folder. (Might need to add
// ability to check for individual global variables.) If it doesn't exist it is created
// along with global variables with default values. Loads control panel.
//----------------------------------------------------------------------------------------------------------
Function Spect_Main()
	String savDF = GetDataFolder(1)
	NewDataFolder/O/S root:Packages

	if( DataFolderExists("Spectrometry"))
		SetDataFolder Spectrometry
      		Variable/G firstrun = 1
      		If(exists("dataType") == 0)
      			Variable/G dataType
      		endif
      		If(exists("fileListHolder") == 0)
      			String/G fileListHolder
      		endif
      		If(exists("pathToFiles") == 0)
      			String/G pathToFiles 
      		endif
      		If(exists("userFolderName") == 0)
      			String/G userFolderName = "default"
      		endif
      		If(exists("userFolderPath") == 0)
      			String/G userFolderPath = "root"
      		endif
      		If(exists("folderTemplateStart") == 0)
      			String/G folderTemplateStart = "_PEDOT"
      		endif
      		If(exists("folderTemplateEnd") == 0)
      			String/G folderTemplateEnd = ".csv"
      		endif
      		If(exists("normalize") == 0)
      			Variable/G normalize
      		endif
      		If(exists("ecal") == 0)
      			Variable/G Ecal
      		endif
      		If(exists("TEYcal") == 0)
      			Variable/G TEYcal
      		endif
      		If(exists("TFYcal") == 0)
      			Variable/G TFYcal
      		endif
	else
		NewDataFolder/S Spectrometry
		Variable/G firstrun = 0
		Variable/G dataType
		String/G fileListHolder
		String/G pathToFiles
		String/G userFolderName = "default"
		String/G userFolderPath = "root"
		String/G folderTemplateStart = "_PEDOT"
		String/G folderTemplateEnd = ".csv"
		Variable/G normalize
		Variable/G Ecal
		Variable/G TEYcal
		Variable/G TFYcal
	endif
	
	if(wintype("loadDataWindow") != 0)
		DoWindow/F loadDataWindow

	elseif(wintype("loadDataWindow") == 0)
		Execute "Spectrometry()"
	endif
	
	SetDataFolder savDF
End
//------------------------------------------------------------------------------------------------------------
// Main control panel and progress bar.
//------------------------------------------------------------------------------------------------------------
Window Spectrometry() : Panel
	PauseUpdate; Silent 1		// building window...
	NewPanel /W=(150,77,490,214)/N=loadDataWindow as "Load Data"
	PopupMenu dataType,pos={18,40},size={139,21},proc=dataTypeAction,title="Select Data Type"
	PopupMenu dataType,mode=3,popvalue="Type",value= #"\"XPS (ADL);XAS (X1B/U4b);XES (X1B);XAS (ALS);XES (ALS);XPS (X24A);Igor File;XPS (ADL) Old;XES 2D;XPS (.pdt)\""
	Button loadFiles,pos={18,99},size={50,20},proc=loadButtonAction,title="Load"
	SetVariable filePath,pos={19,16},size={256,16},title="Files"
	SetVariable filePath,limits={-inf,inf,0},value= root:Packages:Spectrometry:pathToFiles
	Button fileButton,pos={281,14},size={50,20},proc=fileButtonAction,title="Browse"
	SetVariable destFolder,pos={18,70},size={166,16},title="Folder"
	SetVariable destFolder,value= root:Packages:Spectrometry:userFolderName
	CheckBox normalize,pos={207,72},size={64,14},disable=0,title="Normalize"
	CheckBox normalize,variable= root:Packages:Spectrometry:normalize
	CheckBox energyCal,pos={207,86},size={103,14},disable=0,title="Energy Calibration"
	CheckBox energyCal,variable= root:Packages:Spectrometry:Ecal
	CheckBox TEYcal,pos={207,40},size={39,14},disable=2,title="TEY"
	CheckBox TEYcal,variable= root:Packages:Spectrometry:TEYcal
	CheckBox TFYcal,pos={207,58},size={39,14},disable=2,title="TFY"
	CheckBox TFYcal,variable= root:Packages:Spectrometry:TFYcal
	Button cancel,pos={74,99},size={50,20},proc=cancelButtonAction,title="Cancel"
EndMacro

Window ProgressPanel() : Panel
	PauseUpdate; Silent 1		// building window...
	NewPanel /W=(150,77,612,114)/N=ProgressPanel as "Progress Panel"
	ValDisplay valdisp0,pos={8,5},size={443,27},title="Progress"
	ValDisplay valdisp0,limits={0,1,0},barmisc={0,0},highColor= (0,0,0)
	ValDisplay valdisp0,value= _NUM:0
EndMacro
//----------------------------------------------------------------------------------------------------------
// Functions for the control panel.
//----------------------------------------------------------------------------------------------------------
Function dataTypeAction(ctrlName,popNum,popStr) :PopupMenuControl
	String ctrlName
	Variable popNum
	String popStr

	NVAR dataType = root:Packages:Spectrometry:dataType

	dataType = popNum
	if(dataType == 2 || dataType == 4)
		ModifyControl/Z TEYcal disable=0
		ModifyControl/Z TFYcal disable=0
	else
		ModifyControl/Z TEYcal disable=2
		ModifyControl/Z TFYcal disable=2
	endif
End

Function loadButtonAction(ctrlName) :ButtonControl
	string ctrlName
	multiLoad()
	KillWindow loadDataWindow
End

Function fileButtonAction(ctrlName) :ButtonControl
	string ctrlName
	multiOpen()
End

Function cancelButtonAction(B_Struct) :ButtonControl
	STRUCT WMButtonAction &B_Struct
	If(B_Struct.eventCode == 2)
			KillWindow $B_Struct.win
	endif
End
//------------------------------------------------------------------------------------------------------
// Sets the global variables needed to import the files.
//------------------------------------------------------------------------------------------------------
Function multiOpen()
	Variable fileNumber,i,n=0
	SVAR fileListHolder = root:Packages:Spectrometry:fileListHolder
	SVAR pathToFiles = root:Packages:Spectrometry:pathToFiles
	SVAR folderTemplateStart = root:Packages:Spectrometry:folderTemplateStart

	Open/D/R/MULT=1/F="Data Files (*.txt,*.dat,*.csv,*.xas,*.log,*.SPE,*.PRO,*.pdt):.txt,.dat,.csv,.xas,.log,.SPE,.PRO,.pdt;Igor Files (*.pxt, *.ipf):.pxt,.ipf;All Files:.*;" fileNumber
	fileListHolder = s_filename

	i = strsearch(StringFromList(0, fileListHolder, "\r"), ":", Inf, 1)
	pathToFiles = StringFromList(0, fileListHolder, "\r")[0,i]
	NewPath/O/Q pathHolder, pathToFiles

End
//-------------------------------------------------------------------------------------------------------
// Imports the files.
//-------------------------------------------------------------------------------------------------------
Function multiLoad()
	SVAR fileListHolder = root:Packages:Spectrometry:fileListHolder
	SVAR userFolderPath = root:Packages:Spectrometry:userFolderPath
	SVAR userFolderName = root:Packages:Spectrometry:userFolderName
	SVAR folderTemplateStart = root:Packages:Spectrometry:folderTemplateStart
	SVAR folderTemplateEnd = root:Packages:Spectrometry:folderTemplateEnd
	NVAR dataType = root:Packages:Spectrometry:dataType

	string savDF = GetDataFolder(1)
	string fileNameHolder, filePathHolder, extension
	string searchParam = "_"
	string dataFileNameHolder, folderHolder
	variable n,p=0,q=0,i=0,j,k

	n = ItemsInList(fileListHolder, "\r")

	Execute "progresspanel()"
	DoUpDate /W=ProgressPanel /E=1

	string dataFolder = userFolderPath +":"+ userFolderName
	NewDataFolder /O/S $dataFolder
	if (dataType == 2)
		ValDisplay valdisp0, mode=4, win=ProgressPanel,  limits={0,1,0}, barmisc={0,0}, value=_NUM:1
		XAS_Load( stringFromList(p, fileListHolder, "\r"))
	else
		Do
			
			extension = ParseFilePath(4, stringFromList(p, fileListHolder, "\r"), ":", 0, 0)
			fileNameHolder = ReplaceString("." + extension, ParseFilePath(0, stringFromList(p, fileListHolder, "\r"), ":", 1, 0), "")
			filePathHolder = ParseFilePath(1, stringFromList(p, fileListHolder, "\r"), ":", 1, 0)
			folderHolder = ParseFilePath(0,stringFromList(p, fileListHolder, "\r"), ":", 1, 1)
			string waveLoadName = fileNameHolder
			
			ValDisplay valdisp0, win=ProgressPanel,  limits={0,n,0}, barmisc={0,0}, value=_NUM:p+1
			
			if(CheckName(fileNameHolder,10))
				fileNameHolder = "Z_" + fileNameHolder
			endif
			
			If(CheckName(fileNameHolder,11) == CheckName("root",11))
				fileNameHolder = UniqueName(fileNameHolder + "_", 11, 1)
				dataFileNameHolder = CleanupName(fileNameHolder, 0)
				If(stringmatch(dataFileNameHolder, fileNameHolder))
				Else
					//fileNameHolder =  folderHolder + "_" + fileNameHolder
				endif
			Else
				dataFileNameHolder = CleanupName(fileNameHolder, 0)
				If(stringmatch(dataFileNameHolder, fileNameHolder))
				Else
					//fileNameHolder = folderHolder + "_" + fileNameHolder
					If(CheckName(fileNameHolder,11) == CheckName("root",11))
						fileNameHolder = UniqueName(fileNameHolder + "_", 11, 1)
					Else
					endif
				endif
			endif
			string/G root:Packages:Spectrometry:dataFolderName = fileNameHolder
			SVAR dataFolderName = root:Packages:Spectrometry:dataFolderName 
			NewDataFolder /O/S :$dataFolderName
		
			string waveLoadPath = stringFromList(p, fileListHolder, "\r")

		
			if( dataType == 3 || dataType == 5)
				LoadWave/Q/J/D/W/A/H/K=0/B="C=1, F=-1, N=energy; C=1, F=-1, N=counts;" waveLoadName
			elseif (dataType == 1 || dataType == 8)
				defineSensitivityFactors()
				angCorrVersaProbe()
				if (dataType == 8)
				OpenNotebook/P=pathHolder/V=0/N=$dataFolderName stringFromList(p, fileListHolder, "\r")
				Grep /Q /INDX /LIST /E="[[:alpha:]]{1,2}[[:digit:]][[:alpha:]][[:digit:]]*|SUR" stringFromList(p, fileListHolder, "\r")
				Wave W_Index
				WaveStats /Q W_Index
				Variable l=0
				Do
					Notebook $dataFolderName, selection={(W_Index(l),0), (W_Index(l),inf)}
					GetSelection notebook, $dataFolderName, 2
					if(stringmatch(S_selection, "BE_*"))
					else
						if(stringmatch(S_selection, StringFromList(l, S_value, ";")+"\r"))
							Notebook $dataFolderName, selection={(W_Index(l),0), (W_Index(l),inf)}, text="\r\r\r"
							S_selection = ReplaceString("\r", S_selection, "")
							Notebook $dataFolderName, selection={(W_Index(l)+1,0), (W_Index(l)+1,inf)}, text="BE_"+S_selection+","+S_selection
						endif
					endif
					Notebook $dataFolderName, selection={(W_Index(l)+2,0), (W_Index(l)+2,inf)}
					GetSelection notebook, $dataFolderName, 2
					if(stringmatch(S_selection, "1\r"))
						Notebook $dataFolderName, text=""
					endif
					l+=1
				While(l < V_npnts)
				SaveNotebook/O/S=6 $(waveLoadName + ".txt")
				KillWaves /Z W_Index
				KillVariables /Z V_Flag, V_value, V_startParagraph
				KillStrings /Z S_fileName, S_path
				DoWindow /K $dataFolderName
				LoadWave/Q/W/A/G/D/H/K=0 waveLoadName
				elseif(dataType == 1)
				binaryLoad(p,waveLoadName)
				endif
			elseif (dataType == 4)
				OpenNotebook/P=pathHolder/V=0/N=$dataFolderName stringFromList(p, fileListHolder, "\r")
				Notebook $dataFolderName, selection = {(0,0),(0,0)}, findText={"Description Length:", 0}
				if(V_flag)
					Notebook $dataFolderName, selection={(0,0),startOfNextParagraph}, text=""
				endif
				Notebook $dataFolderName, selection = {startOfParagraph,endOfParagraph}
				GetSelection notebook, $dataFolderName, 2
				If(strLen(S_selection) == 1)
					Notebook $dataFolderName, selection = {startOfParagraph,endOfParagraph}, text=""
					Notebook $dataFolderName, selection = {startOfParagraph,endOfParagraph}
					GetSelection notebook, $dataFolderName, 2
				endIf
				If(strLen(S_selection) == 1)
					Notebook $dataFolderName, selection = {startOfParagraph,endOfParagraph}, text=""
					Notebook $dataFolderName, selection = {startOfParagraph,endOfParagraph}
					GetSelection notebook, $dataFolderName, 2
				endIf
				S_selection = replaceString("Energy", S_selection, "Energy_1", 0, 1)
				Notebook $dataFolderName, selection = {startOfParagraph,endOfParagraph}, text=S_selection
				
				String newFile = ParseFilePath(1, waveLoadPath, ":", 1, 0) + "temp.txt"
				newFile = ReplaceString(":", newFile, "\\", 0, inf)
				newFile = ReplaceString(newfile[0], newFile, newfile[0] + ":", 0, 1)
				SaveNotebook /O/S=6 $dataFolderName as newFile
				DoWindow /K $dataFolderName
				LoadWave/O/Q/J/D/W/A/H/K=0 newFile
			elseif (dataType == 6 || dataType == 7)
				LoadData/Q/R waveLoadPath
			elseif (dataType == 9)
				String nameWave = ReplaceString("_dat" , ReplaceString(".", waveLoadName[strSearch(waveLoadName, "XES.", 0), strlen(waveLoadName)], "_"), "")
				LoadWave/O/Q/J/M/U={0,2,1,0}/D/A/K=0/N=$nameWave stringFromList(p, fileListHolder, "\r")
				Wave w1 = $(nameWave + "0")
				DeletePoints/M=1 0,2, w1
				DeletePoints/M=1 (DimSize(w1, 1) - 7), 7, w1
			elseif (dataType == 10)
				Variable refNum
				Open/R/Z=2 refNum as (stringfromlist(p, filelistholder, "\r"))
				readPDT(refNum)
			endif
			SetDataFolder dataFolder
			p += 1
		while (p < n)
		if(dataType == 4)
			DeleteFile newFile
		endif
	endif
KillWindow ProgressPanel
NVAR TEYcal = root:Packages:Spectrometry:TEYcal, TFYcal = root:Packages:Spectrometry:TFYcal, normalize = root:Packages:Spectrometry:normalize, Ecal = root:Packages:Spectrometry:Ecal
If(normalize)
	Spect_Normalize()
endif
If(TEYcal)
	Spect_Normalize()
	XAS_TEY()
endif
If(TFYcal)
	Spect_Normalize()
	XAS_TFY()
endif
If(Ecal)
	XAS_Ecal_Setup()
endif
SetDataFolder savDF

End

//-----------------------------------------------------------------------------------------
//XES_cal calibrates the energy axis of the XES data.
//Will update with database of peak positions.
//Will update to allow different calibrations for different data sets.
//Will update to automate calibration.
//-----------------------------------------------------------------------------------------
function XES_cal(peak1,peak2)
Variable peak1,peak2

variable i,a,b,c1=peak1,c2=peak2,e1,e2,hc,landa1,landa2,j,p,n

//c1=3450//position of first peak
//c2=4400//position of second peak
e1=1011.7/2 //energy of first peak
e2=1034.7/2//energy of second peak
hc=1080

landa1=hc/e1
landa2=hc/e2

b=(landa1-landa2)/(c1-c2)
a=landa1-b*c1

//a=5.2768
//b=-0.001452

string savDF = GetDataFolder(1)
string folderDIR = DataFolderDir (1)
folderDIR = ReplaceString("FOLDERS:", folderDIR, "")
folderDIR = ReplaceString(",", folderDIR, ";")
folderDIR = ReplaceString("\r", folderDIR, "")
j = 0
n = ItemsInList(folderDIR, ";")

Do
	string dataFolderName =stringFromList(j, folderDir, ";")
	SetDataFolder dataFolderName
	
	if(strlen(stringfromlist(j, folderDir, ";")) != 0)
		XES_cal(c1,c2)
	endif
	
	If(waveExists(energy))
       Make/O/N=(numpnts(energy)) energy1

	for (i=0;i<numpnts(energy);i+=1)

       	energy1[i]=hc/(a+b*i)
        
	endfor
	endif
	SetDataFolder savDF
	j += 1
while (j < n)
SetDataFolder savDF
end function

//-------------------------------------------------------------------------------------
//XES_normalize normalizes all XES files.
//Will rewrite to eliminate redundancy with XAS_normalize.
//Will rewrite to allow folder selection.
//-------------------------------------------------------------------------------------
function Spect_normalize()

string savDF = GetDataFolder(1)
string folderDIR = DataFolderDir (1)
folderDIR = ReplaceString("FOLDERS:", folderDIR, "")
folderDIR = ReplaceString(",", folderDIR, ";")
folderDIR = ReplaceString("\r", folderDIR, "")
variable i,j,n,q
	j = 0
	n = 0
	i = ItemsInList(folderDIR, ";")
string normWavelist

normWavelist = "I0;Det;FY;PFY;counts"
q = ItemsInList(normWaveList)

Do
	
	string dataFolderName = stringFromList(j, folderDir, ";")
	setDataFolder dataFolderName
	If(strlen(dataFolderName) != 0)
		Spect_normalize()
	else
	endif
	
	n = 0	
	Do
		string fullpath1 = stringFromlist(n, normWaveList, ";")
      		string fullpath2 = stringFromlist(n, normWaveList, ";") + "_N"
      		If(waveExists($fullpath1))
       		Duplicate/O $fullpath1, $fullpath2
       		WAVE w2 = $fullpath2
			WaveStats/Q w2
			w2 = (w2-V_min)/(V_max-V_min)
		else
		
		endif
		
		n+=1
	While(n < q)
	setDataFolder savDF
 	j += 1
while(j < i)
setDataFolder savDF
end function

//-----------------------------------------------------------------------------------------
//XAS_cal calibrates the energy axis of the XAS data.
//Will update with database of peak positions.
//Will update to allow different calibrations for different data sets.
//Will update to automate calibration.
//-----------------------------------------------------------------------------------------
Function XAS_Ecal_Setup()

String titaniumEdge,titaniumEnergy,oxygenEdge,oxygenEnergy
SVAR  waveSelectionReturnList = root:Packages:waveSelectionReturnList
genericWaveSelection("Select Titanium L-edge Scan", 100, 375, 100, 300, 0, 0, 200, 250)
PauseForUser Wave_Browser
titaniumEdge = Stringfromlist(0,waveSelectionReturnList)
genericWaveSelection("Select Titanium L-edge Energy", 100, 375, 100, 300, 0, 0, 200, 250)
PauseForUser Wave_Browser
titaniumEnergy = Stringfromlist(0,waveSelectionReturnList)
genericWaveSelection("Select Oxygen K-edge Scan", 100, 375, 100, 300, 0, 0, 200, 250)
PauseForUser Wave_Browser
oxygenEdge = Stringfromlist(0,waveSelectionReturnList)
genericWaveSelection("Select Oxygen K-edge Energy", 100, 375, 100, 300, 0, 0, 200, 250)
PauseForUser Wave_Browser
oxygenEnergy = Stringfromlist(0,waveSelectionReturnList)

String scanlist, energylist

scanlist = titaniumEdge + ";" + oxygenEdge
energylist = titaniumEnergy + ";" + oxygenEnergy

Variable lowscan, highscan

Prompt lowscan, "Enter Minimum Scan Number: "		
Prompt highscan, "Enter Maximum Scan Number: "		
DoPrompt "Scan Range", lowscan, highscan

XAS_AutoCal(scanlist,energylist,lowscan,highscan)

end



Function XAS_AutoCal(refScanlist,refEnergylist,lowscan,highscan)

String refScanlist,refEnergylist
Variable lowscan,highscan

String savDF = GetDataFolder(1)

NewDataFolder/O/S root:XAS_Calibration
Make/O/N=6 lit = {458.2,460.9,463.6,465.9,531,533.3}, mono
Make/O/N=4 mono1
Make/O/N=2 mono2
Variable tEdge = 0, p1, p2

SetDataFolder stringfromlist(0,refScanlist)[0,strsearch(stringfromlist(0,refScanlist),":",inf,1)-1]
SetScale x,wavemin($stringfromlist(0,refEnergylist)),wavemax($stringfromlist(0,refEnergylist)),$stringfromlist(0,refScanlist)
Do
	FindPeak/Q/M=(wavemax($stringfromlist(0,refScanlist))*.8)/R=(tEdge,) $stringfromlist(0,refScanlist)
	tEdge = V_TrailingEdgeLoc
	mono1[p1] = V_PeakLoc
	p1+=1
while(p1 < 4)
//mono1 = peak_search($stringfromlist(0,refScanlist),$stringfromlist(0,refEnergylist),5,5)

SetDataFolder stringfromlist(1,refScanlist)[0,strsearch(stringfromlist(1,refScanlist),":",inf,1)-1]
SetScale x,wavemin($stringfromlist(1,refEnergylist)),wavemax($stringfromlist(1,refEnergylist)),$stringfromlist(1,refScanlist)
Do
	FindPeak/Q/M=(wavemax($stringfromlist(1,refScanlist))*.8)/R=(tEdge,) $stringfromlist(1,refScanlist)
	tEdge = V_TrailingEdgeLoc
	mono2[p2] = V_PeakLoc
	p2+=1
while(p2 < 2)
//mono2 = peak_search($stringfromlist(1,refScanlist),$stringfromlist(1,refEnergylist),5,5)

SetDataFolder root:XAS_Calibration

Concatenate/O {mono1,mono2}, mono

//CurveFit/Q/M=2/W=0 line, lit/X=mono/D
K1 = 1;
CurveFit/Q/NTHR=0 line  lit /X=mono /D

SetDataFolder savDF
Wave w1 = root:XAS_Calibration:W_coef
XAS_cal(w1[0],w1[1],lowscan,highscan)
 
end

function XAS_cal(intercept,slope,lowscan,highscan)

Variable intercept, slope, lowscan,highscan

string savDF = GetDataFolder(1)
String savDFName = GetDataFolder(0)
string folderDIR = DataFolderDir (1)
folderDIR = ReplaceString("FOLDERS:", folderDIR, "")
folderDIR = ReplaceString(",", folderDIR, ";")
folderDIR = ReplaceString("\r", folderDIR, "")

variable i,j,n,c1=intercept,c2=slope
	j = 0
	i = ItemsInList(folderDIR, ";")

Do
	Variable/G root:scanNumber
	NVAR scanNum = root:scanNumber
	NVAR dataType = root:Packages:dataType
	if(dataType == 4)
		sscanf savDFName, "%*[^_]_%d%*[^0-9]",scanNum
	else
		sscanf savDFName, "%*[^0-9]%d%*[^0-9]",scanNum
	endif
	SetDataFolder stringfromlist(j, folderDIR, ";")
	if(strlen(stringfromlist(j, folderDir, ";")) != 0)
		XAS_cal(c1,c2,lowscan,highscan)
	endif
	string fullpath1 = "MonoE",fullpath2 = "E_uncal" 
	WAVE w1 = $fullpath1, w2 = $fullpath2
	
	//NVAR scanNumber = root:scanNumber
	If(waveExists(w1))
		Make/N=(numpnts(w1))/O cor_E
		cor_E = c1 + c2*w1
	elseif(waveExists(w2) && scanNum >= lowscan && scanNum <= highscan)
		Make/N=(numpnts(w2))/O cor_E
		cor_E = c1 + c2*w2
	else
	endif
	SetDataFolder savDF
	j += 1
	
While(j < i)

SetDataFolder savDF

end function

//------------------------------------------------------------------------------------------
//XAS_TEY calculates the TEY from the XAS data
//Will update to allow folder selection
//------------------------------------------------------------------------------------------
function XAS_TEY([izeroStr,TEYStr])
String izeroStr,TEYStr

If(paramisdefault(izeroStr))
	izeroStr = "I0"
endIf

If(paramisdefault(TEYStr))
	TEYStr = "Det"
endIf
String/G root:Packages:izeroStrG = izeroStr
String/G root:Packages:TEYStrG = TEYStr
string savDF = GetDataFolder(1)
string folderDIR = DataFolderDir (1)
folderDIR = ReplaceString("FOLDERS:", folderDIR, "")
folderDIR = ReplaceString(",", folderDIR, ";")
folderDIR = ReplaceString("\r", folderDIR, "")
variable i,j,n,panelExit=0
	j = 0
	i = ItemsInList(folderDIR, ";")

Do
       
	string fullpath1 = izeroStr
	string/G root:path1 = fullpath1
	WAVE I0 = $fullpath1
	If(waveExists(I0))
		Duplicate/O I0,I0_temp
	endIf
	WAVE w1 = I0_temp

	string fullpath2 = TEYStr
	string/G root:path2 = fullpath2
	WAVE TEY = $fullpath2
	If(waveExists(TEY))
		Duplicate/O TEY,TEY_temp
	endIf
	WAVE w2 = TEY_temp
	
	string folderpath = stringfromlist(j, folderDIR, ";")
	

	SetDataFolder $folderpath
	

	if(strlen(stringfromlist(j, folderDir, ";")) != 0)
		XAS_TEY(IzeroStr=IzeroStr,TEYStr=TEYStr)
	endif
	
	string currentDF = GetDataFolder(0)

	//Variable scanNumber,scanNumber2
	//sscanf currentDF, "%*[^0-9]%d%*[^0-9]%d",scanNumber,scanNumber2
	
	WaveStats/Q/Z w1
	if(waveExists(w1) && numpnts(w1) >= 15 && V_numNans == 0)
	//Make/N=2/O difference
	
	//for(n=0;n<15;n+=1)
	
	//	difference[n] = w2[n]/w1[n]
		
	//endfor
	
	//wavestats/Q difference
	Variable/G root:firstPoint = 0, root:lastPoint = 15, root:fit_Slope, root:fit_intercept, root:fit_chisqr
	NVAR firstPoint = root:firstPoint, lastPoint = root:lastPoint, fit_Slope = root:fit_Slope, fit_intercept = root:fit_intercept, fit_chisqr = root:fit_chisqr
	CurveFit/M=2/W=0/Q line, w2[firstPoint,lastPoint]/X=w1[firstPoint,lastPoint]/D
	Wave W_coef
	
	root:fit_Slope = W_coef[1]
	root:fit_intercept = W_coef[0]
	root:fit_chisqr = V_chisq/(lastPoint - firstPoint)
	
	Display/N=Fit/K=1/W=(530,300,880,500) w2[5,*] vs w1[5,*]
	ModifyGraph/Z mode($TEYStr)=3,marker($TEYStr)=8,msize($TEYStr)=1.2
	AppendToGraph fit_TEY_temp
	ModifyGraph/Z rgb(fit_TEY_temp) = (0,0,39168),lsize(fit_TEY_temp)=1.5
	

	NewPanel /W=(735,119,947,230)/N=Fit_Panel/K=1
	SetVariable setvar4,pos={20,24},size={85,25},limits={0,lastPoint-1,1},live= 1,value=firstPoint,noproc,title=" "
	SetVariable setvar5, pos={110,24},size={85,25},limits={firstPoint+1,numpnts(w1),1},live=1,value=lastpoint,noproc,title=" "
	ValDisplay fitSlope, value=#"root:fit_Slope"
	ValDisplay fitintercept, value=#"root:fit_intercept"
	ValDisplay fitchisqr, value=#"root:fit_chisqr"
	TitleBox title4,pos={20,5},size={80,13},title="First Point",frame=0
	TitleBox title5,pos={110,5},size={80,13},title="Last Point",frame=0
	Button next,pos={20,80},size={50,20},proc=cancelButtonAction,title="Next"
	ModifyPanel fixedSize=1
	Variable numberOfPoints = numpnts(w1), fpHolder=-1, lpHolder=-1
	
	Do
		PauseForUser/C Fit_Panel
		If(firstPoint == lastPoint && lastPoint != numpnts(w1))
			switch(firstPoint)
				case 0:
					lastPoint += 1
					break
				default:
					firstPoint -= 1
					break
			endswitch 
		endif
		If( (fpHolder != -1 && lpHolder != -1) && (fpHolder != firstPoint || lpHolder != lastPoint))
			CurveFit/M=2/W=0/Q line, w2[firstPoint,lastPoint]/X=w1[firstPoint,lastPoint]/D
			DoUpdate/W=Fit
			Fit_Slope = W_coef[1]
			fit_intercept = W_coef[0]
			fit_chisqr = V_chisq/(lastPoint - firstPoint)
		endif
		fpHolder = firstPoint
		lpHolder = lastPoint
		if(wintype("Fit_Panel") == 0)
			panelExit = 1
		endif
	while(panelExit==0)
	//Variable p1 = 80
	//If(V_chisq >= 300000)
	//	Do
	//		p1 -= 1
	//		CurveFit/M=2/W=0/Q line, det[10,p1]/X=I0[10,p1]/D
	//	while(V_chisq >= 300000)
	//endif

	
	Variable avg = W_coef[1], intercept = W_coef[0], exit = 0
	Variable/G root:holder = avg
	Variable/G root:holder2 = intercept 
	Variable/G root:scale = avg/100
	Variable/G root:interScale = intercept/100
	Variable/G root:interSlope = 1
	Variable/G root:slopeScale = .1
	Variable/G root:secondOrder = 0
	Variable/G root:orderScale = .01
	Variable/G root:thirdOrder = 0
	Variable/G root:thirdScale = .001
	NVAR scaleLocal = root:scale
	NVAR interScaleLocal = root:interScale
	NVAR holder = root:holder
	NVAR holder2 = root:holder2
	NVAR interSlope = root:interSlope
	NVAR slopeScale = root:slopeScale
	NVAR secondOrder = root:secondOrder
	NVAR orderScale = root:orderScale
	NVAR thirdOrder = root:thirdOrder
	NVAR thirdScale = root:thirdScale
	String/G root:curDF = currentDF

	w1 = w1 * avg + intercept
	
	Make/N=(numpnts(w2))/O TEY
	TEY = (w2)/(w1) - 1
	
	//Wave fit_det
	
	//wavestats/Q TEY
	//TEY = (TEY-V_min)/(V_max-V_min)
	
	Display/N=Pause_Graph/K=1/W=(25,50,525,250) w1[5,*],w2[5,*]
	ModifyGraph/Z rgb(I0)=(0,0,39168)
	Display/N=TEY_Graph/K=1/W=(25,300,525,500) TEY[5,*]
	
	
	NewPanel /W=(735,119,1227,230)/N=$currentDF/K=1
	SetVariable setvar0,pos={20,24},size={85,25},limits={-inf,inf,scaleLocal},live= 1,value=_NUM:W_coef[1],proc=scalechange
	SetVariable setvar2, pos={380,24},size={85,25},limits={-inf,inf,interScaleLocal},live=1,value=_NUM:W_coef[0],proc=scalechange
	SetVariable setvar4, pos={290,24},size={85,25},limits={-inf,inf,slopeScale},live=1,value=_NUM:interSlope,proc=scalechange
	SetVariable setvar6, pos={200,24},size={85,25},limits={-inf,inf,orderScale},live=1,value=_NUM:secondOrder,proc=scalechange
	SetVariable setvar8, pos={110,24},size={85,25},limits={-inf,inf,thirdScale},live=1,value=_NUM:thirdOrder,proc=scalechange
	SetVariable setvar1,pos={20,60},size={85,25},limits={0,inf,1},live=1,value=_NUM:scaleLocal,proc=coarseAdjust
	SetVariable setvar3,pos={380,60},size={85,25},limits={0,inf,10},live=1,value=_NUM:interScaleLocal,proc=coarseAdjust
	SetVariable setvar5,pos={290,60},size={85,25},limits={0,inf,.1},live=1,value=_NUM:slopeScale,proc=coarseAdjust
	SetVariable setvar7,pos={200,60},size={85,25},limits={0,inf,.01},live=1,value=_NUM:orderScale,proc=coarseAdjust
	SetVariable setvar9,pos={110,60},size={85,25},limits={0,inf,.001},live=1,value=_NUM:thirdScale,proc=coarseAdjust
	TitleBox title0,pos={20,5},size={80,13},title="I0 Scaling Factor",frame=0
	TitleBox title1,pos={20,41},size={80,13},title="I0 Step Size",frame=0
	TitleBox title2,pos={380,5},size={80,13},title="Intercept Value",frame=0
	TitleBox title3,pos={380,41},size={80,13},title="Intercept Step Size",frame=0
	TitleBox title4,pos={290,5},size={80,13},title="Intercept Slope",frame=0
	TitleBox title5,pos={290,41},size={80,13},title="Slope Step Size",frame=0
	Button nextTEY,pos={20,80},size={50,20},proc=cancelButtonAction,title="Next"
	ModifyPanel fixedSize=1
	
	Do
	PauseForUser/C $currentDF
	if(wintype(currentDF) == 0)
	KillWindow Pause_Graph
	KillWindow TEY_Graph
	Killwindow Fit
	exit = 1
	endif
	while(exit == 0)
	
	endif
	SetDataFolder savDF
	j += 1
while (j < i)
SetDataFolder savDF
end function

Function scalechange(ctrlName,varNum,varStr,varName) : SetVariableControl
String ctrlName
Variable varNum
String varStr
String varName
SVAR izeroStrG = root:packages:izeroStrG,TEYStrG = root:packages:TEYStrG


//NVAR holder = root:holder
//SVAR path1 = root:path1, path2 = root:path2
WAVE w1 = I0_temp
WAVE w2 = TEY_temp
WAVE W_coef
NVAR interSlope = root:interSlope
NVAR secondOrder = root:secondOrder
NVAR thirdOrder = root:thirdOrder
NVAR interScaleLocal = root:interScale
SVAR curDF = root:curDF

If(stringmatch(ctrlName,"setvar0")==1 && varNum != 0)	
	//w1 = w1 * (varNum/W_coef[1]) 
	
	//Make/N=(numpnts(w2))/O TEY
	//TEY = (w2)/(w1)-1
	
	//W_coef[1] = varNum
	
	Variable interVar = w1[0]
	w1 = w1 * (varNum/W_coef[1])
	Variable interVar2 = w1[0] 
	w1 = w1 - (interVar2 - interVar)
	//Print (interVar - interVar2)
	Make/N=(numpnts(w2))/O TEY
	TEY = (w2)/(w1)-1
	W_coef[1] = varNum
	W_coef[0] += (interVar2 - interVar)
	KillControl/W=$curDF setVar2
	SetVariable setvar2, pos={380,24},size={85,25},limits={-inf,inf,interScaleLocal},live=0,value=_NUM:W_coef[0],proc=scalechange
	
Elseif(stringmatch(ctrlName,"setvar2")==1)
	w1 = w1 + (varNum - W_coef[0])
	Make/N=(numpnts(w2))/O TEY
	TEY = (w2)/(w1)-1
	
	W_coef[0] = varNum
Elseif(stringmatch(ctrlName,"setvar4")==1)
	w1[] = w1[p] + ((varNum - interSlope)*(p+1))
	Make/N=(numpnts(w2))/O TEY
	TEY = (w2)/(w1)-1
	
	interSlope = varNum
Elseif(stringmatch(ctrlName,"setvar6")==1)
	w1[] = w1[p] + ((varNum - secondOrder)*(p+1)^2)
	Make/N=(numpnts(w2))/O TEY
	TEY = (w2)/(w1)-1
	
	secondOrder = varNum
Elseif(stringmatch(ctrlName,"setvar8")==1)
	w1[] = w1[p] + ((varNum - thirdOrder)*(p+1)^3)
	Make/N=(numpnts(w2))/O TEY
	TEY = (w2)/(w1)-1
	
	thirdOrder = varNum
endif
end	
//--------------------------------------------------------------------------------------------------------------------------------

function XAS_TFY([izeroStr,TFYStr])
String izeroStr,TFYStr

If(paramisdefault(izeroStr))
	izeroStr = "I0"
endIf

If(paramisdefault(TFYStr))
	TFYStr = "FY"
endIf
string savDF = GetDataFolder(1)
string folderDIR = DataFolderDir (1)
folderDIR = ReplaceString("FOLDERS:", folderDIR, "")
folderDIR = ReplaceString(",", folderDIR, ";")
folderDIR = ReplaceString("\r", folderDIR, "")
variable i,j,n, exit = 0, panelExit = 0
	j = 0
	i = ItemsInList(folderDIR, ";")

Do
       exit = 0
	string fullpath1 = izeroStr
	string/G root:path1 = fullpath1
	WAVE I0 = $fullpath1
	If(waveExists(I0))
		Duplicate/O I0,I0_temp
	endIf
	WAVE w1 = I0_temp

	string fullpath2 = TFYStr
	string/G root:path2 = fullpath2
	WAVE TFY = $fullpath2
	If(waveExists(TFY))
		Duplicate/O TFY,TFY_temp
	endIf
	WAVE w2 = TFY_temp
	
	string folderpath = stringfromlist(j, folderDIR, ";")

	SetDataFolder $folderpath
	
	if(strlen(stringfromlist(j, folderDir, ";")) != 0)
		XAS_TFY(izeroStr=izeroStr, TFYStr=TFYStr)
	endif
	
	string currentDF = GetDataFolder(0)
	
	if(waveExists(w1) && numpnts(w1) >= 15)
	//Make/N=15/O difference
	SetScale x,0,numpnts(w2),w2
	//for(n=0;n<20;n+=1)
	//	difference[n] = w2[n]/w1[n]	
	//endfor
	
	//wavestats/Q difference

     // avg = abs(V_avg)
      //Print scaleFactor
	//w1 = w1 * avg
	//w1 = w1 *(1/4)
	//wavestats/Q w2
	
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)
	
	//wavestats/Q TFY
	//TFY = (TFY-V_min)/(V_max-V_min)
	//Display w1,w2
	
	//Variable/G root:holder = avg
	//Variable/G root:scale = .01
	//NVAR scaleLocal = root:scale
	//NVAR holder = root:holder
	//Display/N=Pause_Graph/K=1/W=(25,50,525,250) w1,w2
	//ModifyGraph rgb(I0_N)=(0,0,39168)
	//Display/N=TFY_Graph/K=1/W=(25,300,525,500) TFY
	
	//NewPanel /W=(735,119,857,230)/N=Panel/K=1
	//SetVariable setvar0,pos={20,24},size={85,16},limits={.005,inf,scaleLocal},live= 1,value=_NUM:avg,proc=scalechangeTFY
	//SetVariable setvar1,pos={20,60},size={85,16},limits={0.01,inf,0.01},live=1,value=_NUM:scaleLocal,proc=coarseAdjust
	//TitleBox title0,pos={20,5},size={80,13},title="I0 Scaling Factor",frame=0
	//TitleBox title1,pos={20,41},size={80,13},title="Step Size Adjust",frame=0
	//Button nextTFY,pos={20,80},size={50,20},proc=cancelButtonAction,title="Next"
	
	Variable/G root:firstPoint = 0, root:lastPoint = 15, root:fit_Slope, root:fit_intercept, root:fit_chisqr
	NVAR firstPoint = root:firstPoint, lastPoint = root:lastPoint, fit_Slope = root:fit_Slope, fit_intercept = root:fit_intercept, fit_chisqr = root:fit_chisqr
	CurveFit/M=2/W=0/Q line, w2[firstPoint,lastPoint]/X=w1[firstPoint,lastPoint]/D
	Wave W_coef
	
	root:fit_Slope = W_coef[1]
	root:fit_intercept = W_coef[0]
	root:fit_chisqr = V_chisq/(lastPoint - firstPoint)
	
	Display/N=Fit/K=1/W=(530,300,880,500) w2[5,*] vs w1[5,*]
	ModifyGraph/Z mode($TFYStr)=3,marker($TFYStr)=8,msize($TFYStr)=1.2
	AppendToGraph fit_TFY_temp
	ModifyGraph/Z rgb(fit_TFY_temp) = (0,0,39168),lsize(fit_TFY_temp)=1.5
	

	NewPanel /W=(735,119,947,230)/N=Fit_Panel/K=1
	SetVariable setvar4,pos={20,24},size={85,25},limits={0,lastPoint-1,1},live= 1,value=firstPoint,noproc,title=" "
	SetVariable setvar5, pos={110,24},size={85,25},limits={firstPoint+1,numpnts(w1),1},live=1,value=lastpoint,noproc,title=" "
	ValDisplay fitSlope, value=#"root:fit_Slope"
	ValDisplay fitintercept, value=#"root:fit_intercept"
	ValDisplay fitchisqr, value=#"root:fit_chisqr"
	TitleBox title4,pos={20,5},size={80,13},title="First Point",frame=0
	TitleBox title5,pos={110,5},size={80,13},title="Last Point",frame=0
	Button next,pos={20,80},size={50,20},proc=cancelButtonAction,title="Next"
	ModifyPanel fixedSize=1
	Variable numberOfPoints = numpnts(w1), fpHolder=-1, lpHolder=-1
	
	Do
		PauseForUser/C Fit_Panel
		If(firstPoint == lastPoint && lastPoint != numpnts(w1))
			switch(firstPoint)
				case 0:
					lastPoint += 1
					break
				default:
					firstPoint -= 1
					break
			endswitch 
		endif
		If( (fpHolder != -1 && lpHolder != -1) && (fpHolder != firstPoint || lpHolder != lastPoint))
			CurveFit/M=2/W=0/Q line, w2[firstPoint,lastPoint]/X=w1[firstPoint,lastPoint]/D
			DoUpdate/W=Fit
			Fit_Slope = W_coef[1]
			fit_intercept = W_coef[0]
			fit_chisqr = V_chisq/(lastPoint - firstPoint)
		endif
		fpHolder = firstPoint
		lpHolder = lastPoint
		if(wintype("Fit_Panel") == 0)
			panelExit = 1
		endif
	while(panelExit==0)

	Variable avg = W_coef[1], intercept = W_coef[0]
	Variable/G root:holder = avg
	Variable/G root:holder2 = intercept 
	Variable/G root:scale = avg/100
	Variable/G root:interScale = intercept/100
	Variable/G root:interSlope = 1
	Variable/G root:slopeScale = .1
	Variable/G root:secondOrder = 0
	Variable/G root:orderScale = .01
	Variable/G root:thirdOrder = 0
	Variable/G root:thirdScale = .001
	NVAR scaleLocal = root:scale
	NVAR interScaleLocal = root:interScale
	NVAR holder = root:holder
	NVAR holder2 = root:holder2
	NVAR interSlope = root:interSlope
	NVAR slopeScale = root:slopeScale
	NVAR secondOrder = root:secondOrder
	NVAR orderScale = root:orderScale
	NVAR thirdOrder = root:thirdOrder
	NVAR thirdScale = root:thirdScale
	String/G root:curDF = currentDF
	
	w1 = w1 * avg + intercept
	
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)-1
	
	//Wave fit_FY
	
	//wavestats/Q TEY
	//TEY = (TEY-V_min)/(V_max-V_min)
	
	Display/N=Pause_Graph/K=1/W=(25,50,525,250) w1[5,*],w2[5,*]
	ModifyGraph/Z rgb(I0)=(0,0,39168)
	Display/N=TFY_Graph/K=1/W=(25,300,525,500) TFY[5,*]
	
	NewPanel /W=(735,119,1227,230)/N=$currentDF/K=1
	SetVariable setvar0,pos={20,24},size={85,25},limits={-inf,inf,scaleLocal},live= 1,value=_NUM:W_coef[1],proc=scalechangeTFY
	SetVariable setvar2, pos={380,24},size={85,25},limits={-inf,inf,interScaleLocal},live=0,value=_NUM:W_coef[0],proc=scalechangeTFY
	SetVariable setvar4, pos={290,24},size={85,25},limits={-inf,inf,slopeScale},live=1,value=_NUM:interSlope,proc=scalechangeTFY
	SetVariable setvar6, pos={200,24},size={85,25},limits={-inf,inf,orderScale},live=1,value=_NUM:secondOrder,proc=scalechangeTFY
	SetVariable setvar8, pos={110,24},size={85,25},limits={-inf,inf,thirdScale},live=1,value=_NUM:thirdOrder,proc=scalechangeTFY
	SetVariable setvar1,pos={20,60},size={85,25},limits={0,inf,1},live=1,value=_NUM:scaleLocal,proc=coarseAdjust
	SetVariable setvar3,pos={380,60},size={85,25},limits={0,inf,10},live=1,value=_NUM:interScaleLocal,proc=coarseAdjust
	SetVariable setvar5,pos={290,60},size={85,25},limits={0,inf,.1},live=1,value=_NUM:slopeScale,proc=coarseAdjust
	SetVariable setvar7,pos={200,60},size={85,25},limits={0,inf,.01},live=1,value=_NUM:orderScale,proc=coarseAdjust
	SetVariable setvar9,pos={110,60},size={85,25},limits={0,inf,.001},live=1,value=_NUM:thirdScale,proc=coarseAdjust
	TitleBox title0,pos={20,5},size={80,13},title="I0 Scaling Factor",frame=0
	TitleBox title1,pos={20,41},size={80,13},title="I0 Step Size",frame=0
	TitleBox title2,pos={380,5},size={80,13},title="Intercept Value",frame=0
	TitleBox title3,pos={380,41},size={80,13},title="Intercept Step Size",frame=0
	TitleBox title4,pos={290,5},size={80,13},title="Intercept Slope",frame=0
	TitleBox title5,pos={290,41},size={80,13},title="Slope Step Size",frame=0
	Button nextTEY,pos={20,80},size={50,20},proc=cancelButtonAction,title="Next"
	ModifyPanel fixedSize=1
	
	Do
		PauseForUser/C $currentDF
		if(wintype(currentDF) == 0)
			KillWindow Pause_Graph
			KillWindow TFY_Graph
			KillWindow Fit
			exit = 1
		endif
	while(exit == 0)
	
	//Killwaves difference
	endif
	SetDataFolder savDF
	j += 1
	
while (j < i)

SetDataFolder savDF
end function

Function coarseAdjust(ctrlName,varNum,varStr,varName) : SetVariableControl
String ctrlName
Variable varNum
String varStr
String varName
If(stringmatch(ctrlName,"setvar1") && varNum != 0)
	NVAR scale = root:scale
	scale = varNum
	ModifyControl/Z setvar0 limits={.005,inf,scale}
Elseif(stringmatch(ctrlName,"setvar3"))
	NVAR interscale = root:interscale
	interscale = varNum
	ModifyControl/Z setvar2 limits={-inf,inf,interscale}
Elseif(stringmatch(ctrlName,"setvar5"))
	NVAR slopeScale = root:slopeScale
	slopeScale = varNum
	ModifyControl/Z setvar4 limits={-inf,inf,slopeScale}
Elseif(stringmatch(ctrlName,"setvar7"))
	NVAR orderScale = root:orderScale
	orderScale = varNum
	ModifyControl/Z setvar6 limits={-inf,inf,orderScale}
Elseif(stringmatch(ctrlName,"setvar9"))
	NVAR thirdScale = root:thirdScale
	thirdScale = varNum
	ModifyControl/Z setvar8 limits={-inf,inf,thirdScale}
endif
end

Function scalechangeTFY(ctrlName,varNum,varStr,varName) : SetVariableControl
String ctrlName
Variable varNum
String varStr
String varName
//NVAR holder = root:holder
//SVAR path1 = root:path1, path2 = root:path2
WAVE w1 = I0_Temp
WAVE w2 = TFY_Temp
WAVE W_coef
NVAR interSlope = root:interSlope
NVAR secondOrder = root:secondOrder
NVAR thirdOrder = root:thirdOrder
NVAR interScaleLocal = root:interScale
SVAR curDF = root:curDF
	
If(stringmatch(ctrlName,"setvar0")==1)	
	Variable interVar = w1[0]
	w1 = w1 * (varNum/W_coef[1])
	Variable interVar2 = w1[0] 
	w1 = w1 - (interVar2 - interVar)
	//Print (interVar - interVar2)
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)-1
	W_coef[1] = varNum
	W_coef[0] += (interVar2 - interVar)
	KillControl/W=$curDF setVar2
	SetVariable setvar2, pos={380,24},size={85,25},limits={-inf,inf,interScaleLocal},live=0,value=_NUM:W_coef[0],proc=scalechangeTFY
	
Elseif(stringmatch(ctrlName,"setvar2")==1)
	w1 = w1 + (varNum - W_coef[0])
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)-1
	
	W_coef[0] = varNum
Elseif(stringmatch(ctrlName,"setvar4")==1)
	w1[] = w1[p] + ((varNum - interSlope)*(p+1))
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)-1
	
	interSlope = varNum
Elseif(stringmatch(ctrlName,"setvar6")==1)
	w1[] = w1[p] + ((varNum - secondOrder)*(p+1)^2)
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)-1
	
	secondOrder = varNum
Elseif(stringmatch(ctrlName,"setvar8")==1)
	w1[] = w1[p] + ((varNum - thirdOrder)*(p+1)^3)
	Make/N=(numpnts(w2))/O TFY
	TFY = (w2)/(w1)-1
	
	thirdOrder = varNum
endif
end	
//--------------------------------------------------------------------------------------------------------------------------------
function reNameWaves()

string savDF = GetDataFolder(1)
string folderDIR = DataFolderDir (1)
folderDIR = ReplaceString("FOLDERS:", folderDIR, "")
folderDIR = ReplaceString(",", folderDIR, ";")
folderDIR = ReplaceString("\r", folderDIR, "")
variable i,j,n
	j = 0
	i = ItemsInList(folderDIR, ";")

Do
	string folderpath = savDF + "'" + stringfromlist(j, folderDIR, ";") + "'"
	SetDataFolder $folderpath
	Rename Counter_1, Det
	Rename Counter_2, FY
	Rename Counter_3, I0
	Rename Counter_4, PFY
	KillWaves/Z Counter_0,Counter_5,wave0,Ph_E
	SetDataFolder savDF
	j+=1
while (j < i-1)

end function

//--------------------------------------------------------------------------------------------------------------------------------

function XAS_Load( waveLoadName)
String waveLoadName

Variable refNum
Open /R/Z=2/T=".log" refNum as waveLoadName
String fullpath = S_filename
Variable lineNumber = 0, scanNumber, k=0
String Buffer
do
		FReadLine refNum, buffer
		lineNumber += 1

		// Check for EOF
		if (strlen(buffer) == 0)
			return lineNumber
		endif
		
		// Check for first line of scan
		// #S 1  ascan  vz3 -0.05 0.05  50 3
		if ( stringmatch( buffer, "#S*" ) == 1 )
			scanNumber = -1 // Reset the scan number
			sscanf buffer, "#S %d *", scanNumber
		endif
			
		if     ( stringmatch( buffer, "#S*ascan*" ) == 1 )
			lineNumber = ParseSpecxas_scan( refNum, lineNumber, scanNumber )
		elseif ( stringmatch( buffer, "#S*timescan*" ) == 1 )
			lineNumber = ParseSpecxas_scan( refNum, lineNumber, scanNumber )
		elseif ( stringmatch( buffer, "#S*EscanBU*" ) == 1 )
			lineNumber = ParseSpecxas_scan( refNum, lineNumber, scanNumber )
		elseif ( stringmatch( buffer, "#S*xas_scan*" ) == 1 )
			lineNumber = ParseSpecxas_scan( refNum, lineNumber, scanNumber )
		elseif ( stringmatch( buffer, "#S*Escan*" ) == 1 )
			lineNumber = ParseSpecxas_scan( refNum, lineNumber, scanNumber )
		else
		endif
while(1)
end

Function binaryLoad(p1,waveLoadName)
Variable p1
String waveLoadName
SVAR fileListHolder = root:Packages:Spectrometry:fileListHolder
SVAR userFolderPath = root:Packages:Spectrometry:userFolderPath
SVAR userFolderName = root:Packages:Spectrometry:userFolderName
SVAR folderTemplateStart = root:Packages:Spectrometry:folderTemplateStart
SVAR folderTemplateEnd = root:Packages:Spectrometry:folderTemplateEnd
SVAR pathToFiles = root:Packages:Spectrometry:pathToFiles
SVAR dataFolderName = root:Packages:Spectrometry:dataFolderName 
Variable p2 = 0, p3 = 0, p4 = 0, p6 = 0 ,fileRefNum, holder, endOfNums
String strHolder
Variable numSteps, stepSize, highE, lowE, numScans,totBytes, numRegions = 1
String scanName,energyWave, waveNoteTemp = ""

	Open/R fileRefNum as stringfromlist(p1, fileListHolder, "\r")
	NewNotebook/V=0/F=0/K=1/N=$dataFolderName as dataFolderName
	
Do
	FReadLine fileRefNum, strHolder
	if(!stringMatch(strHolder,"SOFH\r") && !stringMatch(strHolder,"EOFH\r"))
		waveNoteTemp = waveNoteTemp + strHolder
	endif
	Notebook $dataFolderName, text=strHolder
	if(strsearch(strHolder,"NoSpectralReg:",0) != -1)
		sscanf strHolder, "%*s %g", numScans
		Make/T/O/N=(numScans,0) scanInfo
	elseif (strsearch(strHolder,"SpectralRegDef:",0) != -1)
		sscanf strHolder, "%*s %*g %*g %s %*g %g %g %g %g %*g %*g %*g %*g %*s", scanName, numSteps, stepSize, highE, lowE
		scanInfo[p3][] = {{scanName}, {num2str(numSteps)}, {num2str(stepSize)}, {num2str(highE)}, {num2str(lowE)}}
		p3+=1
	elseif (strsearch(strHolder,"NoDPDataCyc:",0) != -1)
		sscanf strHolder, "%*s %g", numRegions
	endif
	p6 += 1
while(strsearch(strHolder,"EOFH",0) == -1)
	FStatus fileRefNum
	Variable garbageInt, numOfScansInt, byteOffsetInt, doubleFloat
	FBinRead/B=3/F=3 fileRefNum, garbageInt
	FBinRead/B=3/F=3 fileRefNum, numOfScansInt
	FBinRead/B=3/F=3 fileRefNum, byteOffsetInt
	FStatus fileRefNum
	if(numRegions!=1)
		FSetPos fileRefNum, (V_filePos + byteOffsetInt + 4 + 2*numScans*numRegions*8)
	else
		FSetPos fileRefNum, (V_filePos + byteOffsetInt + 4)
	endif
	p2 = 0
	p3 = 0
	Do
		Variable p5 = 0
		if(numRegions == 1)
			if(CheckName(scanInfo[p3][0],1))
				scanInfo[p3][0] = UniqueName(scanInfo[p3][0] + "_",1,1)
			endif
		
			Make/O/N=(str2num(scanInfo[p3][1])) $scanInfo[p3][0]
			energyWave = "BE_" + scanInfo[p3][0]
			Make/O/N=(str2num(scanInfo[p3][1])) $energyWave
			Wave w1 = $scanInfo[p3][0]
			Wave w2 = $energyWave
			Notebook $dataFolderName, text="\r"+scanInfo[p3][0] +"\r\r"
		endif
		Do
			p4 = 0
			if(numRegions != 1)
				String wNameHolder = scanInfo[p3][0] + "_"+ num2str(p5+1)
				Make/O/N=(str2num(scanInfo[p3][1])) $wNameHolder
				energyWave = "BE_" + wNameHolder
				Make/O/N=(str2num(scanInfo[p3][1])) $energyWave
				Wave w1 = $wNameHolder
				Wave w2 = $energyWave
				Notebook $dataFolderName, text="\r"+ wNameHolder +"\r\r"
			endif
			Do
					Variable numHolder
					FBinRead/B=3/F=5 fileRefNum, numHolder
					sprintf strHolder, "%.40f\r", numHolder
					Notebook $dataFolderName, text=strHolder
					w1[p4] = numHolder
					w2[p4] = str2num(scanInfo[p3][3]) +p4*str2num(scanInfo[p3][2])
					p4+=1
			while(p4 < str2num(scanInfo[p3][1]))
				Setscale/I x,str2num(scanInfo[p3][3]),str2num(scanInfo[p3][4]), w1
				Variable p7 = 0
				Variable numberOfKeyValues = ItemsInlist(waveNoteTemp,"\r")
				Do
					Note w1, stringFromList(p7,waveNoteTemp,"\r")
					p7+=1
				while(p7 < 40)
					Note w1, stringFromList(p7+p3,waveNoteTemp,"\r")
				p7 +=numScans
				Do
					Note w1, stringFromList(p7,waveNoteTemp,"\r")
					p7+=1
				while(p7 < numberOfKeyValues)
				xpsCorrAngVP(w1)
				Notebook $dataFolderName,text="\r"
				p5+=1
		while(p5 < numRegions)
		p3+=1
	while(p3 < numScans)
	FStatus fileRefNum	
	Close fileRefNum
	SaveNoteBook/O$dataFolderName as pathToFiles + waveLoadName + ".dat"
	DoWindow/K $dataFolderName

KillWaves/Z scanInfo
Close/A
end

Function ParseSpecxas_scan( refNum, lineNumber, scanNumber )
	Variable refNum, lineNumber, scanNumber

	printf "s%d: xas_scan (line %d) \r", scanNumber, lineNumber
	
	String savedDataFolder = GetDataFolder(1)
	String dataFolderName
	sprintf dataFolderName, "s%03d_xas_scan", scanNumber
	NewDataFolder /O/S :$dataFolderName
	
	// Variables to extract from scan data
	Variable numPoints = 1			// Number of points in scan (unknown)
	String column_title_list = ""
	String parse_format_list = ""
	String variable_list = ""
	String values_list = ""
	
	Variable E_cal_val, E_uncal_val, Seconds_val, I0_val, FY_val, FY_val2, Det_val, Refs_val, Temp_val
	Variable p1

	// Loop vars	
	String buffer
	Variable firstChar
	Variable len
	Variable i = 0
	do
		ValDisplay valdisp0, mode=4, win=ProgressPanel,  limits={0,1,0}, barmisc={0,0}, value=_NUM:1
		FReadLine refNum, buffer
		lineNumber += 1
		
		len = strlen(buffer)
		firstChar = char2num(buffer[0])
		//print firstChar
		// 13 = EOL
		// 35 = "#"
		// 45 = "-"
		if (len == 0)
			For(p1 = 0; p1 < itemsInList(values_list); p1 += 1)
				NVAR holderVar = $(stringFromList(p1,column_title_list) + "_Var")
				KillVariables/Z holderVar
			endFor
			SetDataFolder savedDataFolder
			return lineNumber						// End of file
		elseif (firstChar==13)						// End of scan block
			For(p1 = 0; p1 < itemsInList(values_list); p1 += 1)
				NVAR holderVar = $(stringFromList(p1,column_title_list) + "_Var")
				KillVariables/Z holderVar
			endFor
			SetDataFolder savedDataFolder
			return lineNumber
		elseif (firstChar==35) 					// Comment line
			if(char2num(buffer[1]) == 76)
				column_title_list = ""
				For(p1 = 0; p1 < itemsinlist(buffer[2,inf], " "); p1 +=1)
					if(strlen(stringfromlist(p1, buffer[2,inf], " ")))
						if(stringmatch(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), ""),"*Time*"))
							column_title_list = AddListItem(UniqueName(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), ""),1,1), column_title_list, ";", inf)
							Variable/G $(UniqueName(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), ""),1,1) + "_Var")
							Make/O/N=(numPoints) $(UniqueName(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), ""),1,1))
						else
							column_title_list = AddListItem(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), ""), column_title_list, ";", inf)
							Variable/G $(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), "") + "_Var")
							Make/O/N=(numPoints) $(replaceString("\r",stringfromlist(p1, buffer[2,inf], " "), ""))
						endif
					else
					endif
				endFor
			endif
		else 											// Data line (needs to be parsed)
			values_list = ""
			if (i >= numPoints)
				numPoints += 1
			endif
			For(p1 = 0; p1 < itemsinlist(buffer, " "); p1 += 1)
				if(strlen(stringfromlist(p1, buffer, " ")))
					values_list = AddListItem(replaceString("\r",stringfromlist(p1, buffer, " "), ""), values_list, ";", inf) 
				endif
			endFor
			For(p1 = 0; p1 < itemsInList(values_list); p1 += 1)
				NVAR holderVar = $(stringFromList(p1,column_title_list) + "_Var")
				Wave holderWave = $(stringFromList(p1,column_title_list))
				holderVar = str2num(stringFromList(p1,values_list))
				Redimension/N=(numPoints) holderWave
				holderWave[i] = holderVar
			endFor
			i += 1
		endif
	while(1)
End

Function makeSomeVariables(listOfVariables)
String listOfVariables
Variable p1

For(p1 = 0; p1 < itemsinlist(listOfVariables, " "); p1 += 1)
	Variable/G $(stringFromList(p1,listOfVariables," "))
endFor
For(p1 = 0; p1 < itemsinlist(listOfVariables, " "); p1 += 1)
	NVAR holderVar = $(stringFromList(p1,listOfVariables," "))
	holderVar = p1
endFor
end

Function readRGA()
Variable/D refNum, logging, maxMass, pntsPerMass, pntsPerScan, p1, dataValue, p2 = 0
String stringHolder

Open/R/F="RGA Analog Scans (*.ana):.ana;All Files:.*;" refNum
FReadline/T=(num2char(0)) refNum, stringHolder
Print StringHolder
FStatus refNum
FSetPos refNum, (V_filepos + 14)
FBinRead/F=2 refNum, logging
FBinRead/F=2 refNum, maxMass
FBinRead/F=2 refNum, pntsPerMass
FBinRead/F=2 refNum, pntsPerScan
Print logging, maxMass, pntsPerMass, pntsPerScan
Make/D/Free/O/N=(pntsPerScan) scanWave
Make/D/Free/O/N=(pntsPerScan) scanMatrixHolder
Make/D/O/N=(pntsPerScan) $(ParseFilePath(3,ParseFilepath(5,S_filename,":",0,0), ":", 0, 0)[16,20])
Wave scanMatrix = $(ParseFilePath(3,ParseFilepath(5,S_filename,":",0,0), ":", 0, 0)[16,20])

FReadline/T=(num2char(0)) refNum, stringHolder
Print StringHolder
FStatus refNum
FSetPos refNum, (V_filepos + 9)
String dateTimeList = ""
Do
	FReadline/T=(num2char(128)) refNum, stringHolder
	dateTimeList =  AddlistItem(stringHolder[0,strlen(stringHolder)-4], dateTimeList, ";", inf)
	FStatus refNum
	FSetPos refNum, (V_filepos + 22)
	For(p1 = 0; p1 < pntsPerScan; p1 += 1)
		FBinRead/F=4 refNum, dataValue
		dataValue = abs(dataValue)
		dataValue = log(dataValue)
		scanWave[p1] = dataValue
	endFor
	if(p2)
		Concatenate/O {scanMatrixHolder,scanWave}, scanMatrix
	else
		scanMatrixHolder = scanWave
		scanMatrix = scanMatrixHolder
	endif
	Duplicate/O scanMatrix,scanMatrixHolder
	FStatus refNum
	p2 += 1
While(V_filePos < V_logEOF)
Close refNum
SetScale/I x,1,maxMass,scanMatrix
Make/O/N=(itemsinlist(dateTimeList, ";"))/T dateTimeWave
For(p1 = 0; p1 < itemsinList(dateTimeList); p1 += 1)
	dateTimeWave[p1] = stringFromList(p1, dateTimeList)
EndFor
For(p1 = 0; p1 < dimsize(scanMatrix,0); p1 += 1)
	For(p2 = 0; p2 < dimSize(scanMatrix,1); p2 += 1)
		if(numtype(scanMatrix[p1][p2]))
			scanMatrix[p1][p2] = -18
		endif
	endFor
endFor
splitMat("scanMatrix")
end

Function readPDT(refNum)
Variable refNum
Variable tempDouble,tempLongInt,filePos,numScanRegions,p1,p2
Variable lowE,eRange,passE,unknown,eStep,tStep
String string32 = "",string28 = "",regionName = "",listOfRegionNames = "", tempString
string32 = PadString(string32,32,0x20)
string28 = PadString(string28,28,0x20)
regionName = PadString(regionName,10,0x20)
String header = ""

//Open/R/F="PDT files (*.pdt):.pdt;All Files:.*;" refNum
FBinRead/B=3 refNum, string32
sscanf string32, "%[A-Za-z0-9 .]", tempString
header += "SoftwareVersion: " + tempString + "\r"

FBinRead/B=3/F=5 refNum, tempDouble
//Print tempDouble

FSetPos refNum, 108

FBinRead/B=3/F=5 refNum, tempDouble
header += "IntensityCalCoeff: " + num2Str(tempDouble) + " "

FBinRead/B=3/F=5 refNum, tempDouble
header += num2str(tempDouble) + "\r"

FBinRead/B=3/F=3 refNum, tempLongInt
numScanRegions = tempLongInt
header += "NumberOfScans: " + num2str(tempLongInt) + "\r"

FSetPos refNum, 144

header += "MachineInfo: "
For(p1 = 0; p1 < 2; p1 += 1)
FBinRead/B=3 refNum, string28
sscanf string28, "%s", tempString
header += tempString + " "
EndFor
header += "\r"

FBinRead/B=3/F=5 refNum, tempDouble
header += "AnalyserWorkFcn: " + num2str(tempDouble) + " eV\r"

FSetPos refNum, 228

header += "StagePosition: "
For(p1 =0; p1 < 5; p1 += 1)
FBinRead/B=3/F=5 refNum, tempDouble
header += num2str(tempDouble) + " "
endFor
header += "\r"

FSetPos refNum, 280

FBinRead/B=3/F=5 refNum, tempDouble
//Print tempDouble

FSetPos refNum, 292

FBinRead/B=3/F=5 refNum, tempDouble
//Print tempDouble
FBinRead/B=3/F=5 refNum, tempDouble
//Print tempDouble

For(p1 = 0; p1 <= numScanRegions; p1 += 1)
	FBinRead/B=3 refNum, regionName
	FBinRead/B=3/F=5 refNum, lowE
	FBinRead/B=3/F=5 refNum, eRange
	FBinRead/B=3/F=5 refNum, passE
	FBinRead/B=3/F=5 refNum, unknown
	FBinRead/B=3/F=5 refNum, eStep
	FBinRead/B=3/F=5 refNum, tStep
	FBinRead/B=3/F=3 refNum, tempLongInt
	if(p1 < numScanRegions)
		String regionNameX
		sscanf regionName, "%s", regionNameX
		Make/O/N=(eRange/eStep+1) $(regionNameX)
		SetScale/P x,lowE+eRange,-eStep,$(regionNameX)
		Note/NOCR $(regionNameX), header
		header += regionNameX + ": " + num2str(lowE) + " " + num2str(eRange) + " " + num2str(passE) + " " + num2str(unknown) + " " + num2str(eStep) + " " + num2str(tStep) + " " + num2str(tempLongInt) + "\r"
		listOfRegionNames = AddListItem(regionNameX, listOfRegionNames,";",inf)
		Make/O/N=(eRange/eStep+1) $("BE_" + regionNameX)
	endif
endFor

For(p1 = 0; p1 < 3; p1 += 1)
FBinRead/B=3/F=5 refNum, tempDouble
//Print tempDouble
EndFor

For(p1 =0; p1 < 2; p1 += 1)
FBinRead/B=3/F=3 refNum, tempLongInt
//Print tempLongInt
EndFor

For(p1 = 0; p1 < 6; p1 += 1)
FBinRead/B=3/F=5 refNum, tempDouble
//Print tempDouble
EndFor

Make/O/N=(numScanRegions) maskWave 
For(p1 = 0; p1 <= numScanRegions+3; p1 += 1)
	FBinRead/B=3/F=3 refNum, tempLongInt
	If(p1 && p1 <= numpnts(maskWave))
		maskWave[p1 - 1] = tempLongInt
	Else
		//Print tempLongInt
	EndIf
endFor

For(p1 = 0; p1 < numScanRegions; p1 += 1)
	Wave tempWave = $("BE_" + stringfromList(p1, listOfRegionNames))
	Note tempWave, header
	For(p2 = 0; p2 < numPnts(tempWave); p2 += 1)
		FBinRead/B=3/F=5 refNum, tempDouble
		tempWave[p2] = tempDouble
	endFor
endFor

For(p1 = 0; p1 < numScanRegions; p1 += 1)
	Wave tempWave = $(stringfromList(p1, listOfRegionNames))
	Note tempWave, header
	For(p2 = 0; p2 < numPnts(tempWave); p2 += 1)
		FBinRead/B=3/F=5 refNum, tempDouble
		tempWave[p2] = tempDouble
	endFor
endFor

For(p1 = 0; p1 < numPnts(maskWave); p1 += 1)
	If(!maskWave[p1])
		KillWaves/Z $stringFromList(p1, listOfRegionNames), $("BE_" + stringFromList(p1, listOfRegionNames))
	endIf
endFor

KillWaves/Z maskWave

End